<template>
	<div id="map">
		<div id="header">
			<div id="r-result">
				<div id="chufa">
					<div class="div_input">
						<span>出发地:</span>
						<input type="search" id="suggestId1" size="20" style="width:222px;" v-model="searchText1" ref="input_search1" />
						<button @click="dingwei" id="dingwei">
							<img src="../assets/dingwei.png" class="dingwei-img">
						</button>
					</div>
					<div id="searchResultPanel1" style="border:1px solid #C0C0C0;width:150px;height:auto;display: none; ">

					</div>
				</div>
				<div id="mudi" v-show="hasCarAndType != 5  ">
					<div class="div_input">
						<span>目的地:</span>
						<input type="search" id="suggestId" size="20" style="width:222px;" v-model="searchText" ref="input_search" />
					</div>
					<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto;display: none; ">
					</div>
				</div>
				<div v-if="hasCarAndType == 1 || hasCarAndType == 2">
					<mt-button type="primary" class="btn-class" @click="runCar(1)" v-if="hasCarAndType == 1 ">进行导航</mt-button>
					<mt-button type="danger" class="btn-class" @click="runCar(2)" v-else>取消导航</mt-button>
				</div>
				<div v-if="hasCarAndType == 3 || hasCarAndType == 4 || hasCarAndType ==5">
					<div v-if="hasCarAndType == 4 || hasCarAndType == 3">
						公交车辆
						<mt-button type="primary" @click="runCar(3)" class="btn-class" v-if="hasCarAndType == 3 ">公交开始运行</mt-button>
						<mt-button type="danger" @click="runCar(4)" class="btn-class" v-else>公交结束运行</mt-button>
					</div>

					<div v-if="hasCarAndType == 5">用户车辆为公交车辆，但未设置公交路线</div>
				</div>

			</div>
		</div>
		<div class="div_map">
			<allmap :arrPois1="arrPois" :run="run" :info="car" :nowRoute="nowRoute" :hasCarAndType="hasCarAndType"
			 v-on:changeState='changeHasCarAndType' :routes='routes'></allmap>
		</div>

	</div>
</template>

<script>
	import BMap from 'BMap'
	import allmap from './component.vue'
	export default {
		data() {
			return {
				searchText: '', //目的地
				searchText1: '', //出发地
				searchReuslt: '',
				arrPois: [],
				flag: false, //是否正在导航
				dingweiLoc: '', //定位的地点
				searchFlag: false, //查询中
				isDriving: false,
				user: '',
				nowLoc: {
					lon: '',
					lat: ''
				},
				loc: '',
				point: null,
				run: 0,
				car: '',
				nowRoute: '', // 车辆行驶路线
				routes: '', // 公交车辆路线
				/*
				0为没有车，
				1 为有车且类型不为公交，没有在行驶，2为有车且类型不为公交，正在行驶，
				3 车的类型为公交,未行驶 , 4 车的类型为公交,行驶中,5 车的类型为公交,未设置路线
				*/
				hasCarAndType: 10,
			}

		},
		components: {
			allmap
		},
		computed: {
			UserCar() {
				return this.$store.state.car
			}
		},
		watch: {
			searchText: function(val1, val2) {
				if (this.car.state == 1) {
					return;
				}
				if (val1 == '') {
					this.arrPois.splice(1, 1);
				}
				if (this.hasCarAndType == 1 || this.hasCarAndType == 0)
					this.search('suggestId', 0, "searchResultPanel")
			},
			searchText1: function(val) {
				if (this.dingweiLoc == val) {
					return;
				}
				if (val == '') {
					this.arrPois.splice(0, 1);
				}
				if (this.hasCarAndType == 0) {
					this.search('suggestId1', 1, "searchResultPanel1")
				}
			},
			routes: function(val) {
					
					if (val) {
						this.searchText1 = val[0].name
						this.searchText = val[val.length - 1].name

						if (this.$refs.input_search && this.$refs.input_search1) {
							this.$refs.input_search.value = val[val.length - 1].name;
							this.$refs.input_search.readOnly = 'readOnly';
							this.$refs.input_search1.value = val[0].name;
							this.$refs.input_search1.readOnly = 'readOnly';
						}

					} else {
						this.searchText1 = '未设置路线'
						this.$refs.input_search1.value = '未设置路线';
						this.$refs.input_search1.readOnly = 'readOnly';
					}
				
			},
			hasCarAndType: function(val, old) {
				if (old == 2 && val == 1) {
					this.hasCarAndType = 10;
					this.run = 0;
					this.getCarInfoByNum(this.user.car)
					this.searchText = ''
					this.$refs.input_search.readOnly = ''

				}else if (old == 4 && val == 3) {
					this.routes ='';
					this.run = 0;
					this.getCarInfoByNum(this.user.car)
					
				}
				 else {
					switch (val) {
						case 1:
							{
								let point = new BMap.Point(this.car.cur_loc_lon, this.car.cur_loc_lat);
								this.nowRoute = null;
								this.getLocation(point);
								this.arrPois.splice(0, 1, point)

							}
							break;
						case 2:
							{
								/* this.arrPois[0] 存放进行路书的初始位置（车辆当前位置）
															 this.arrPois[1] 存放进行路书的目的位置（目的地位置）
															 this.arrPois[2] 存放进行的出发地（出发点）
															*/
								if (this.searchText == '') {
									this.run = 1;
									let point0 = new BMap.Point(this.nowRoute.cur_loc_lon, this.nowRoute.cur_loc_lat);
									this.arrPois.splice(0, 1, point0)
									let point1 = new BMap.Point(this.nowRoute.dep_place_lon, this.nowRoute.dep_place_lat);
									this.getLocation(point1);
									let point2 = new BMap.Point(this.nowRoute.des_lon, this.nowRoute.des_lat);
									this.getLocation(point2, 2);
									this.arrPois.splice(1, 1, point2)
									this.arrPois.splice(2, 1, point1)

								} else {
								}
							}
							break;
						case 4:{
							this.run = 3
						}break;
					}
				}
			}
		},
		beforeDestroy() {
			this.lushu = null;
		},
		created() {
			this.user = this.$store.state.user[0];
			if (this.user.car == null) {
				this.hasCarAndType = 0;
			} else {
				this.getCarInfoByNum(this.user.car)
			}
		},
		updated() {
			if (this.routes) {
				this.$refs.input_search.value = this.routes[this.routes.length - 1].name;
				this.$refs.input_search.readOnly = 'readOnly';
				this.$refs.input_search1.value = this.routes[0].name;
				this.$refs.input_search1.readOnly = 'readOnly';
			}
		},
		methods: {
			changeHasCarAndType(data) {
				this.hasCarAndType = data;
			},
			getLocation(point, num = 1) { // 地址解析 参数num判断出发地还是目的地 默认1（出发点），2目的地

				let geoc = new BMap.Geocoder();
				geoc.getLocation(point, (result) => {
					let addComp = result.addressComponents;
					let loc = addComp.province + addComp.city + addComp.district + addComp.street +
						addComp.streetNumber;
					if (num == 1) {
						this.dingweiLoc = loc;
						this.searchText1 = loc;
						this.$refs.input_search1.readOnly = 'readOnly'
					}
					if (num == 2) {
						this.searchText = loc;
						this.$refs.input_search.value = loc
						this.$refs.input_search.readOnly = 'readOnly'
					}
				})

			},
			dingwei() {
				if (this.hasCarAndType == 1 || this.hasCarAndType == 5) {
					var _that = this;
					var geolocation = new BMap.Geolocation();
					geolocation.enableSDKLocation();
					geolocation.getCurrentPosition(function(r) {
						if (this.getStatus() == BMAP_STATUS_SUCCESS) {
							var p0 = r.point.lng;
							var p1 = r.point.lat;
							let point = new BMap.Point(p0, p1);
							_that.arrPois.splice(0, 1, point);
							var address = '';
							address += r.address.province;
							address += r.address.city;
							address += r.address.district;
							address += r.address.street;
							address += r.address.street_number;
							_that.searchText1 = address;
							_that.dingweiLoc = address;
						} else {
							alert('failed' + this.getStatus());
						}
					});
				}


			},

			search(id, sure, searchResultPanel) { // sure 确定  1出发地 还是 0目的地 



				function G(id) {
					return document.getElementById(id);
				}


				var ac = new BMap.Autocomplete( //建立一个自动完成的对象
					{
						"input": id,
						"location": map,

					});
				ac.addEventListener("onhighlight", e => { //鼠标放在下拉列表上的事件
					var str = "";
					var _value = e.fromitem.value;
					var value = "";
					if (e.fromitem.index > -1) {
						value = _value.province + _value.city + _value.district + _value.street + _value.business;
					}
					str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

					value = "";
					if (e.toitem.index > -1) {
						_value = e.toitem.value;
						value = _value.province + _value.city + _value.district + _value.street + _value.business;
					}
					str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;

					if (sure == 0) { //目的地
						this.searchText = value

					} else if (sure == 1) { //出发地
						this.searchText1 = value;

					}
					G(searchResultPanel).innerHTML = str;

				});

				var myValue;
				ac.addEventListener("onconfirm", e => { //鼠标点击下拉列表后的事件
					var _value = e.item.value;
					myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
					G(searchResultPanel).innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

					setPlace(this, sure);
				});

				function setPlace(_that, sure) {
					map.clearOverlays(); //清除地图上所有覆盖物
					let myGeo = new BMap.Geocoder();

					function myFun() {
						let pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
						let rs = local.getResults().getPoi(0);
						if (sure == 0) { //目的地

							_that.searchReuslt = rs;
							let p0 = rs.point.lng;
							let p1 = rs.point.lat;
							// var checksum = makerArry[i].checksum;
							let point = new BMap.Point(p0, p1); //118.230272,33.482474
							_that.arrPois.splice(1, 1, point);

						} else if (sure == 1) { //出发地
							_that.searchReuslt = rs;
							let p0 = rs.point.lng;
							let p1 = rs.point.lat;
							// var checksum = makerArry[i].checksum;
							let point = new BMap.Point(p0, p1); //118.230272,33.482474
							_that.arrPois.splice(0, 1, point);;
						}


						map.centerAndZoom(pp, 11);
						map.addOverlay(new BMap.Marker(pp)); //添加标注
						setTimeout(() => {
							_that.searchFlag = false;
						}, 1000)

					}
					let local = new BMap.LocalSearch(map, { //智能搜索
						onSearchComplete: myFun
					});
					local.search(myValue);

				}

			},

			getCarInfoByNum(car_num) {
				this.$axios.get('/api/info/carInfoByNum', {
						params: {
							num: car_num
						}
					})
					.then(data => {
						if (data.status == 200) {
							this.$store.commit('setUserCar', data.data)
							let car = data.data[0]
							this.nowLoc.lat = car.cur_loc_lat;
							this.nowLoc.lon = car.cur_loc_lon;
							this.car = car;

							let point = new BMap.Point(car.cur_loc_lat, car.cur_loc_lon)
							if (this.car.type == '公交') {
								this.getBusRoutes(this.car.id, this.car.state)
							} else {
								if (this.car.state == 0) {
									this.hasCarAndType = 1;
								} else if (this.car.state == 1) {
									this.getDrivngInfo();
								}
							}

						}
					})
					.catch(err => {
						console.log(err)
					})
			},
			runCar(val) {
				if (val == 1) {
					this.run = 1;
				} else if (val == 2) {
					this.run = 2;
				} else if (val == 3) {
					this.run = 3;
				} else if (val == 4) {
					this.run = 4;
				}
			},
			getDrivngInfo() { //正在行驶的车辆不能 导航按钮
				this.$axios.get('/api/info/drivingInfo', {
						params: {
							user_id: this.user.id
						}
					})
					.then(data => {
						if (data.status == 200) {
							if (data.data.length != 0) {
								this.nowRoute = data.data[0];

								this.hasCarAndType = 2;
							}
						}
					})
					.catch(err => {
						console.log(err)
					})
			},
			getBusRoutes(car_id, carState = 0) { //获取公交车辆路线，参数车辆id ， 车辆状态（默认0）
				this.$axios.get('/api/car/getBusRoutes', {
						params: {
							car_id: car_id
						}
					})
					.then(data => {
						if (data.data == 'no') {
							this.routes = null;
							this.hasCarAndType = 5;
						} else {
							let departure = JSON.parse(data.data[0].departure)
							let destination = JSON.parse(data.data[0].destination)
							let way = JSON.parse(data.data[0].way)
							let routes = []
							routes = routes.concat(departure);
							routes = routes.concat(way);
							routes = routes.concat(destination);
							this.routes = routes;
							this.searchText = routes[0].name;
							this.searchText1 = routes[routes.length - 1].name;

							this.$store.commit('setBusRoutes', routes)
							if (carState == 0) {
								this.hasCarAndType = 3
							} else if (carState == 1) {
								this.hasCarAndType = 4
							}

						}
					})
					.catch(err => {
						console.log(err)
					})
			},
		},

	}
</script>

<style scoped lang="less">
	/* 放大缩小地图控件 */
	.BMap_stdMpZoom {
		margin-top: 50px;
	}

	#map {
		position: relative;
		width: 100%;
		height: 615 px;

		#header {
			width: 100%;
			height: 50px;
			position: fixed;
			top: 3px;
			z-index: 12;
			background-color: rgba(0, 245, 250, 0.7);
			border-radius: 5px 5px 10px 10px;

			#r-result {
				position: relative;
				width: 100%;

				.search-position(@l) {
					position: absolute;
					top: 15px;
					left: @l;
					width: 350px;
					color: #000;
				}

				#chufa {
					.search-position(88px);
				}

				#mudi {
					.search-position(500px);
				}

				.btn-class {
					color: #fff;
					position: absolute;
					top: 3px;
					right: 40px;
				}
			}


			.div_input::after {
				content: '';
				height: 0;
				display: block;
				clear: both;
				visibility: hidden;
			}

			.div_input {
				width: 100%;
				height: 52px;
				float: left;
				text-align: left;

			}

			#dingwei {
				padding: 0
			}

			.dingwei-img {
				width: 16px;

				height: 16px;

			}
		}


		.div_map {
			width: 100%;
			height: 600px;
			top: 40px;

			position: relative;

			#allmap {
				position: absolute;

				height: 600px;
				top: 0;

				width: 100%;
			}
		}

	}
</style>
